#include "laurin-80211-network.h"
#include "../laurin-utils.h"


Laurin80211Network::Laurin80211Network(Glib::ustring ssid)
{
	_ssid = ssid;
}


Laurin80211Network::~Laurin80211Network()
{
	_stations.clear();
	_access_points.clear();
}


Glib::ustring Laurin80211Network::getSSID() const
{
	return _ssid;
}


Laurin80211AccessPoint* Laurin80211Network::isAccessPointPresent(Glib::ustring bssid)
{
	std::list<Laurin80211AccessPoint>::iterator b = _access_points.begin();
	std::list<Laurin80211AccessPoint>::iterator e = _access_points.end();


	while( b != e )
	{


		if(getReadableMAC(b->getMAC()) == bssid)
			return &(*b);
		else
		{
			u_int8_t* internalmac = generatePreviousMAC(b->getMAC());
			if(getReadableMAC(internalmac) == bssid)
			{
				free(internalmac);
				return &(*b);
			}
		}


		b++;
	}

	return NULL;
}


Laurin80211AccessPoint* Laurin80211Network::isAccessPointPresent(u_int8_t* bssid)
{
	return isAccessPointPresent(getReadableMAC(bssid));
}


Laurin80211Station* Laurin80211Network::isStationPresent(u_int8_t* mac)
{
	std::list<Laurin80211Station>::iterator b = _stations.begin();
	std::list<Laurin80211Station>::iterator e = _stations.end();


	while( b != e )
	{
		if(areMACEquals(b->getMAC(), mac))
			return &(*b);

		b++;
	}

	return NULL;
}


Laurin80211Station* Laurin80211Network::isDevicePresent(u_int8_t* mac)
{
	Laurin80211Station* s = isStationPresent(mac);
	if(s == NULL)
		s = (Laurin80211AccessPoint*) isAccessPointPresent(mac);

	return s;
}


bool Laurin80211Network::addAccessPoint(const Laurin80211AccessPoint& accessPoint, bool check)
{
	if(check && isAccessPointPresent(accessPoint.getBSSID()))
		return false;

	_access_points.push_front(accessPoint);
	return true;
}


bool Laurin80211Network::addStation(const Laurin80211Station& station, bool check)
{
	if(check && isStationPresent(station.getMAC()))
		return false;

	_stations.push_front(station);
	return true;
}


std::list<Laurin80211Station>* Laurin80211Network::getStations()
{
	return &_stations;
}


std::list<Laurin80211AccessPoint>* Laurin80211Network::getAccessPoints()
{
	return &_access_points;
}


void Laurin80211Network::setDistanceBetweenMonitorAndAP(Glib::ustring bssid, double distance)
{

	Laurin80211AccessPoint* tmp = isAccessPointPresent(bssid);
	if( tmp != NULL)
	{

		tmp->setDistanceFromMonitor(distance);

		std::list<Laurin80211Station>::iterator b = _stations.begin();
		std::list<Laurin80211Station>::iterator e = _stations.end();

		while(b != e)
		{
			if(areMACEquals(b->getBSSID(), tmp->getBSSID()))
			{
				b->setDistanceBetweenMonitorAndAP(distance);
			}

			b++;
		}

	}
}

